package com.yulp.springboot2task.job;


import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 异步通知-定时处理
 *
 * @date: 2017/8/24.
 * @author: yulipeng.
 *
 * 可以作废
 */
@Component
public class NotifyScheduler {

    private static final Logger logger = LoggerFactory.getLogger(NotifyScheduler.class);

    @Autowired
    private Scheduler scheduler;


    /**
     * 定时发送消息
     *
     * @param afterTime   多少毫秒后开始执行
     * @param everyTime   每多少秒执行一次
     * @param sendNum     执行n+1次
     * @param orderNo     订单唯一识别号
     * @param jobType 订单来源
     * @throws SchedulerException
     */
    public void sendNotify(long afterTime, int everyTime, int sendNum, String orderNo, String jobType) {
        logger.info("开始定时调度-Scheduler========>:{},jobType:{}", orderNo, jobType);



        //创建一个JobDetail实例，该实例与NotifyQuartzJob.class绑定
        JobDetail jobDetail = JobBuilder.newJob(NotifyQuartzJob.class)
                //设置参数
                .usingJobData("orderNo", orderNo)
                .usingJobData("jobType", jobType)
                // jobName
                .withIdentity(orderNo, "fkJob_group").build();

        //当前时间x毫秒后
        Date date = new Date();
        date.setTime(date.getTime() + afterTime);

        //设置执行规则
        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                //triggerName
                .withIdentity(orderNo, "ztTri_group")
                //这个时间开始执行
                .startAt(date)
                .withSchedule(SimpleScheduleBuilder
                        .simpleSchedule()
                        //每x秒执行一次
                        .withIntervalInSeconds(everyTime)
                        //发送n+1次
                        .withRepeatCount(sendNum))
                .build();

        try {
            scheduler.start();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            logger.error("定时异步通知异常:" + e.getMessage(), e);
        }
    }
}
